package cn.monkey.transport.netty.server.codec.protocol.tcp.http.ws;

import cn.monkey.transport.netty.server.codec.protocol.tcp.http.HttpServerProtocolPredicate;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.HttpHeaderNames;

public interface WebsocketServerProtocolPredicate extends HttpServerProtocolPredicate {

    WebsocketServerProtocolPredicate INSTANCE = new WebsocketServerProtocolPredicate() {
    };


    @Override
    default boolean test(Channel channel, ByteBuf byteBuf) {
        if (!HttpServerProtocolPredicate.super.test(channel, byteBuf)) {
            return false;
        }
        String s = new String(byteBuf.array());
        String[] split = s.split("\n");

        for (String line : split) {
            String[] pair = line.split(": ");
            if (pair.length != 2) {
                continue;
            }
            if (HttpHeaderNames.UPGRADE.contentEqualsIgnoreCase(pair[0])) {
                String upgradeVal = pair[1].trim();
                return "WEBSOCKET".equalsIgnoreCase(upgradeVal);
            }
        }
        return false;
    }
}
